import { defineStore } from 'pinia'
import { reactive } from 'vue'
import { ApiGetUserInfo } from '@/services/apis/user'

import type { IUser } from './interfaces/user.interface'

export const useUserStore = defineStore(
  'user',
  () => {
    const user = reactive<IUser>({})

    function setUserInfo(userInfo: IUser & { user: string }, token: string) {
      user.uid = userInfo.uid
      user.phone = userInfo.phone
      user.username = userInfo.user
      user.avatar = userInfo.avatar
      user.token = token
    }

    getUserInfo(localStorage.getItem('token') || '')
    async function getUserInfo(token: string) {
      const userInfo = await ApiGetUserInfo()
      setUserInfo(userInfo, token)

      localStorage.setItem('authTimeout', new Date().getTime() + 1000 * 60 * 60 * 24 * 2 + '')
    }

    function logout(this: { $reset: () => void }) {
      this.$reset()
    }

    return {
      user,

      getUserInfo,
      logout
    }
  },
  {
    persist: {
      key: 'user-store'
    }
  }
)
